package com.edu.controller;

import com.edu.Result;
import com.edu.StatusCode;
import com.edu.pojo.EduNotice;
import com.edu.service.EduNoticeService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 公告处理控制层
 *
 * @author YJF
 */
@RestController
@RequestMapping("/nts")
public class EduNoticeController {

    @Autowired
    private EduNoticeService eduNoticeService;

    /**
     * 分页条件获取公告列表信息
     */
    @GetMapping("/list")
    public Result findByPage(HttpServletRequest request) {
        int page = Integer.parseInt(request.getParameter("page"));
        int size = Integer.parseInt(request.getParameter("size"));
        String info = request.getParameter("info");
        String start = "";
        String end = "";
        if (info.length() > 1) {
            start = info.split(",")[0];
            end = info.split(",")[1];
        }
        PageInfo<EduNotice> ntsList = eduNoticeService.findByPage(page, size, start, end);
        return new Result(true, StatusCode.OK, "查询成功!", ntsList);
    }

    /**
     * 添加公告信息
     */
    @PostMapping("/add")
    public Result addNts(@RequestBody EduNotice eduNotice) {
        int status = eduNoticeService.addNts(eduNotice);
        if (status == StatusCode.OK) {
            return new Result(true, StatusCode.OK, "添加成功!", eduNotice);
        } else if (status == StatusCode.OVER_LIMIT) {
            return new Result(false, StatusCode.OVER_LIMIT, "文本内容超出限制!", eduNotice);
        }
        return new Result(false, StatusCode.ERROR, "添加失败!", eduNotice);
    }

    /**
     * 根据公告ID查询公告信息
     */
    @GetMapping("/one/{id}")
    public Result findById(@PathVariable("id") Integer id) {
        EduNotice eduNotice = eduNoticeService.findById(id);
        return new Result(true, StatusCode.OK, "查询成功!", eduNotice);
    }

    /**
     * 更新公告信息
     */
    @PutMapping("/update")
    public Result updateNts(@RequestBody EduNotice eduNotice) {
        int status = eduNoticeService.updateNts(eduNotice);
        if (status == StatusCode.OK) {
            return new Result(true, StatusCode.OK, "更新成功!", eduNotice);
        }
        return new Result(false, StatusCode.ERROR, "更新失败!", eduNotice);
    }

    /**
     * 根据公告ID删除公告
     */
    @DeleteMapping("/del/{id}")
    public Result delNts(@PathVariable("id") Integer id) {
        int status = eduNoticeService.delNtsById(id);
        if (status == StatusCode.OK) {
            return new Result(true, StatusCode.OK, "删除成功!", id);
        }
        return new Result(false, StatusCode.ERROR, "删除失败!", id);
    }
}
